<script setup>
import {ref} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import ChannelSelect from './ChannelSelect.vue'
import { articleGetArticleDetailService, articlePublishArticle ,articleUpdateArticle} from '@/api/article'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { baseURL } from '@/utils/request'
import { imageUrlToFile } from '@/utils/imageUrlToFile'
import { ElMessage } from 'element-plus'
// 组件渲染需要的数据
const defaultFormModel = ref({
  //文章标题
  title:'',
  //分类的id
  cate_id:'',
  //文章封面的图片-file对象
  cover_img:'',
  //文章的发布状态:草稿/已发布
  //文章内容
  content:'',
  state:''

})
// 与表单双向绑定的数据formModel

const formModel = ref()
formModel.value = JSON.parse(JSON.stringify(defaultFormModel.value))

// 控制抽屉组件弹出或隐藏
const drawer = ref(false)
// 图片上传的相关逻辑
const imageUrl = ref('')
const selectImg = (UploadFile)=>{
  imageUrl.value = URL.createObjectURL(UploadFile.raw)
  formModel.value.cover_img = imageUrl.value
}

const quillEditorRef = ref()
// 抽屉组件的内置方法
const open = async (row)=>{
  //row不为空对象,则是编辑文章
  if(Object.keys(row).length !== 0){
    //根据文章id向后台请求文章详情数据，进行表单渲染，以修改文章
    const res = await articleGetArticleDetailService(row.id)
    formModel.value = res.data.data
    drawer.value = true
    imageUrl.value = baseURL + formModel.value.cover_img
    // 数据准备好,开启抽屉组件

    formModel.value.id = row.id
  }else{
 //row为空,表单数据渲染也为空
    // 重置图片上传里的内容
    imageUrl.value = ''
    // 重置富文本编辑器文本内容
    // editorRef.value.setHTML('')
    drawer.value = true

  }
}

// 抽屉组件关闭前触发事件执行函数
const formRef =ref()
const closeDrawer = ()=>{
  formRef.value.resetFields()
  // 清空富文本编辑器里的内容
  quillEditorRef.value.setHTML('')
}
const emit = defineEmits(['success'])
// 发布文章/草稿按钮的逻辑
const handlePublishArticle = async (state)=>{
  formModel.value.state = state
  formModel.value.cover_img = await imageUrlToFile(imageUrl.value,formModel.value.cover_img)
  //将数据对象formModel转换成form-data的格式
  const formData = new FormData()
  for (let key in formModel.value) {
    formData.append(key, formModel.value[key])
  }
  if(formModel.value.id){
    //文章id存在就向后台服务器发送文章修改请求
    const res = await articleUpdateArticle(formData)
    ElMessage.success(res.data.message)
    emit('success','update')
  }else{
    //向后台服务器发送新增文章请求
    const res = await articlePublishArticle(formData)
    ElMessage.success(res.data.message)
    emit('success','add')
  }
  drawer.value = false

}
//表单数据的校验规则
const rules = ref({
  title:[
  { required: true, message: '请输入文章标题', trigger: 'blur' },
  { min: 2, max: 20, message: '文章标题长度为2-20个字符', trigger: 'blur' },
  ],
  content:[
  { required: true, message: '请输入文章内容', trigger: 'blur' },
  { min: 2, max: 20, message: '文章标题长度为2-200个字符', trigger: 'blur' },
  ]
})
//文章内容校验逻辑
// 文章内容的校验状态:''/'error'/'validating'/'successs'
const contentValidateStatus = ref('')
const errorMessage = ref('')
const onContentChange = ()=>{
  if(!formModel.value.content){
    contentValidateStatus.value = 'error'
    errorMessage.value = '请输入文章内容'
  }else{
    contentValidateStatus.value = 'success'
    errorMessage.value = ''
  }
}
defineExpose({
  open
})
</script>
<template>
  <el-drawer
      v-model="drawer"
      :title="formModel.id ? '编辑文章' : '添加文章'"
      size="50%"
      @close="closeDrawer"

    >
     <el-form :model="formModel" :rules="rules" ref="formRef">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select
          v-model="formModel.cate_id"
          width="100%"
        >
        </channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="selectImg"
          :auto-upload="false"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content" :validate-status="contentValidateStatus" :error="errorMessage">
        <!-- 富文本编辑器组件 -->
        <div class="editor">
          <quill-editor
           theme="snow"
           v-model:content="formModel.content"
           content-type="html"
           ref="quillEditorRef"
            @blur="onContentChange"
           >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlePublishArticle('已发布')">发布</el-button>
        <el-button type="info" @click="handlePublishArticle(草稿)">草稿</el-button>
      </el-form-item>
     </el-form>
    </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
